<template>
    <div class="l-set-user">
        <el-button size="mini" type="primary" @click="createUser" class="user-button">新建用户</el-button>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="index" width="50">
            </el-table-column>
            <el-table-column prop="admin_name" label="姓名">
            </el-table-column>
            <el-table-column prop="admin_status" label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.admin_status" active-color="#409eff" inactive-color="#dfdfdf" :active-value="1" :inactive-value="2" @change="handlerState(scope.row)"/>
                </template>
            </el-table-column>
            <el-table-column prop="admin_addtime" label="创建账号时间">
                <template slot-scope="scope">
                    {{formatDate(scope.row.admin_addtime)}}
                </template>
            </el-table-column>
            <el-table-column prop="action" label="操作" width="260">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="fixPassword(scope.row)">修改密码</el-button>
                    <el-button size="small" type="" @click="setUpdate(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="intDel(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination :page-size="page.size" :pager-count="7" layout="prev, pager, next" :total="page.total" :current-page="page.page" @current-change="handlerPage">
        </el-pagination>


        <el-dialog :title="dialog.title" :visible.sync="dialogVisible" :close-on-click-modal="false" class="dislog-user" width="600px"> 
            <div>
                <el-row type="flex">
                    <el-col :span="6" class="j-user-label">登录账户：</el-col>
                    <el-col :span="18">
                        <el-input style="width:350px;" v-model="user.admin_name" placeholder="请填入登录账户" />
                    </el-col>
                </el-row>
                <el-row v-if="page_status == 'add'">
                    <el-col :span="6" class="j-user-label">登录密码：</el-col>
                    <el-col :span="18">
                        <el-input style="width:350px;" v-model="user.admin_password" type="password" placeholder="请填入登录密码" />
                        <p class="j-user-tips">*提示：密码必须包含字母、数字。长度6位以上 例：abcd123</p>
                    </el-col>
                </el-row>
                <el-row type="flex" v-if="page_status == 'add'">
                    <el-col :span="6" class="j-user-label">确认密码：</el-col>
                    <el-col :span="18">
                        <el-input style="width:350px;" v-model="repeat_password" type="password" placeholder="再次输入登录密码" />
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col :span="6" class="j-user-label">用户身份：</el-col>
                    <el-col :span="18">
                        <el-select v-model="user.admin_role" clearable placeholder="请选择用户身份">
                            <el-option v-for="(item,index) in userLevel" :key="index" :label="item" :value="index+1">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="j-user-label">用户权限块：</el-col>
                    <el-col :span="18">
                    	  <el-checkbox-group v-model="user.admin_rule">
								<el-checkbox v-for="(item,index) in permit_group" :key="index" :label="item._id"  v-if="item.rule_group_status == 1"  >{{item.rule_group_name}}</el-checkbox>
						  </el-checkbox-group>
                    </el-col>
                </el-row>

                <el-row type="flex">
                    <el-col :span="6" class="j-user-label">用户状态：</el-col>
                    <el-col :span="18">
                        <el-radio-group v-model="user.admin_status">
                            <el-radio :label="1">激活</el-radio>
                            <el-radio :label="2">禁用</el-radio>
                        </el-radio-group>
                    </el-col>
                </el-row>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" v-if="dialog.cancel" @click="dialogVisible = false">{{dialog.cancel}}</el-button>
                <el-button size="small" type="primary" @click="intAction">{{dialog.determine}}</el-button>
            </div>
        </el-dialog>



    </div>
</template>
<script type="text/javascript">
import { get_rule_group_all } from '@/api/permit'
import { get_user_total , get_user_all , get_user_one , add_user , edit_user , del_user} from '@/api/user'
export default {
    data() {
        return {
        	// 页面状态
        	page_status:'add',
        	// 所有权限组
        	permit_group:[],
        	repeat_password:'',  //再次输入密码  验证
        	// 用户等级设置
            userLevel: ['高级管理员', '中级管理员', '初级管理员', "普通用户"],
            // 单个用户信息
            user:{
                admin_name: "",
                admin_password: "",
                admin_status: "", //用户状态   启用 or 禁用
                admin_role: "", //管理员等级
                admin_rule: [], //账号权限
            },

            tableData: [],


            // 分页配置
            page: {
                page: 1, //当前页面
                size: 10, //每页显示大小
                total: 100, //页面总数
            },

            // 模态框配置
            dialogVisible:false,
            dialog:{
            	title:'创建用户',
            	cancel:"取消",
            	determine:'创建'
            }
        }
    },
    mounted(){
    		// 获取所有权限组
			this.getPermitAll();
			// 获取所有用户
			this.getUserAll();
            // 获取用户总量
            this.getUserTotal();
    },
    methods: {
        /**
         * 创建用户
         * @return {[type]} [description]
         */
        createUser() {
        	this.dialog = {
        		title:'创建新用户',
        		cancel:'取消',
        		determine:'创建'
        	};
        	this.page_status = 'add';
        	this.user = {
                admin_rule: [], //账号权限
        	};
        	this.dialogVisible = true;
        },
        /**
         * 更新账号
         * @param {[type]} data [description]
         */
        setUpdate(data) {
            this.dialog = {
                title:'更新账号',
                cancel:'取消',
                determine:"更新"
            }
            this.page_status = 'edit';
            this.getUserDetail(data);
            this.dialogVisible = true;
        },


        /**
         * 修改密码
         * @return {[type]} [description]
         */
        fixPassword(data){
            /**
             * 1、修改低权限密码时，可直接修改密码
             * 2、修改自身的密码时，需验证登录密码
             */

             console.log('修改密码开发中...',data);
        },

        /**
         * 删除账号
         * @return {[type]} [description]
         */
        intDel(data) {
            this.permit = JSON.parse(JSON.stringify(data));
            this.$confirm('此操作将永久删除该账号, 是否继续?', '系统提示', {
              confirmButtonText: '继续',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                this.delData(data);
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
        },



        /**
         * 模态框功能
         * @return {[type]} [description]
         */
        intAction(){
        	switch(this.page_status){
        		case 'add':
        			this.addUser();
        		break;
                case 'edit':
                    this.editUser();
                break;
        	}
        },




        /**
         * 分页功能
         * @return {[type]} [description]
         */
        handlerPage(page) {
            this.page.page = page;
            this.getUserAll();
        },


        /**
         * 将时间戳转换为日期格式
         * @param  {[type]} value [description]
         * @return {[type]}       [description]
         */
        formatDate (value) { // 时间戳转换日期格式方法
           return new Date(parseInt(value)).toLocaleString().replace(/:\d{1,2}$/,' '); 
        },

        /**
         * 检测输入数据
         * @return {[type]} [description]
         */
        checkData(){
            //    密码规则
            //      密码至少包含 数字和英文，长度6-20
            // 
            var ret = false;
            var tips = "";
            var password  = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
            if(!this.user.admin_name){
                tips = "请填入账号名称！";
                ret  = true;
            }else if(this.page_status == 'add' && !this.user.admin_password){
                tips = "请填入账号密码！";
                ret  = true;
            }else if(this.page_status == 'add' && !password.test(this.user.admin_password)){
                tips = "密码不符合规则！";
                ret  = true;
            }else if(!this.user.admin_role){
                tips = "请设置用户身份！";
                ret  = true;
            }else if(this.user.admin_rule.length <1 ){
                tips = "请设置账号权限";
                ret  =  true;
            }else if(!this.user.admin_status){
                tips = "请设置账号状态";
                ret  = true;
            }else if(this.page_status == 'add'){
                if(this.user.admin_password != this.repeat_password){
                    tips = "两次输入的密码不一致！";
                    ret  = true;
                }
            }

            if(ret){
                this.$message({
                    message: tips,
                    type: 'warning'
                });
                return false;
            }

            return true;

        },

        /********************    数据处理     *********************/
        /**
         * 获取所有权限组
         * @return {[type]} [description]
         */
        getPermitAll(){
	    	get_rule_group_all().then(response => {
	    		this.permit_group = response;
	    	})
        },

        /**
         * 获取用户详情
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        async getUserDetail(data){
            await get_user_one(data).then(response => {
                if(response){
                    this.user = response
                }
            })
        }, 

        /**
         * 直接修改用户状态
         * @return {[type]} [description]
         */
        handlerState(data){
            // console.log('data',[data.admin_status]);
            var parems = {
                _id:data._id,
                admin_status:data.admin_status
            }

            edit_user(parems).then(response => {
              this.$message({
                message: '更新用户成功！',
                type: 'success'
              });
            })
        },

        /**
         * 获取用户总数
         * @return {[type]} [description]
         */
        getUserTotal(){
            get_user_total().then(response => {
                if(typeof response == 'number'){
                    this.page.total = response;
                }
            })
        },

        /**
         * 获取用户
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        getUserAll(){
        	get_user_all(this.page).then(response => {
        		console.log('所有用户',response);
        		if(Array.isArray(response)){
        			this.tableData = response;
        		}else{
        			this.tableData = [];
        		}
        	})
        },

        /**
         * 创建用户
         */
        addUser(){
        	// 判断
            if(!this.checkData()){ return false}
        	add_user(this.user).then(response => {
              this.$message({
                message: '创建用户成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getUserAll();
        	})
        },
        /**
         * 更新用户
         * @return {[type]} [description]
         */
        editUser(){
            if(!this.checkData()){ return false}
            console.log('user',this.user);
            edit_user(this.user).then(response => {
              this.$message({
                message: '更新用户成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getUserAll();
            })
        },
        /**
         * 删除用户
         * @return {[type]} [description]
         */
        delData(data){
            del_user(data).then(response => {
                this.$message({
                    message: '删除用户成功！',
                    type: 'success'
                });
                this.getUserAll();
            })
        }
    }
}
</script>
<style type="text/css" lang="scss">
.l-set-user {
    .user-button {
        margin-bottom: 10px;
    }
    .el-pagination {
        text-align: right;
        margin-top: 8px;
        padding-right: 1px;
    }


}
.el-row--flex {
    align-items: center;
    margin-bottom: 15px;

    &:last-child {
        margin-bottom: 0px;
    }
}
.el-select-dropdown {
    .el-scrollbar:not(.el-menu--collapse) {
        min-height: 0px;
    }
}
.dislog-user {
	.el-checkbox-group{
		margin-bottom: 5px;
	}
    .el-checkbox__label {
        margin-bottom: 10px;
    }	
    .j-user-label {
        text-align: right;
    }

    .j-user-tips {
      color:red;
      font-size: 12px;
      padding: 0px;
      margin: 0px;
      margin-bottom: 15px;
    }
}
</style>